const express = require('express');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const rateLimit = require('express-rate-limit');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100 // 限制每个IP每15分钟最多100个请求
});
app.use(limiter);

// 文件上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    const uniqueName = `${uuidv4()}-${file.originalname}`;
    cb(null, uniqueName);
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB限制
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件 (JPEG, PNG, GIF, WebP)'));
    }
  }
});

// 模拟数据库
let articles = [
  {
    id: 1,
    title: '如何学习前端开发',
    category: 'technology',
    theme: '前端开发',
    keywords: '前端,学习,开发',
    content: '<p>前端开发是一个不断发展的领域，需要持续学习新技术...</p>',
    status: 'published',
    createdAt: '2024-01-15',
    updatedAt: '2024-01-15'
  },
  {
    id: 2,
    title: '我的旅行日记',
    category: 'travel',
    theme: '旅行',
    keywords: '旅行,日记,体验',
    content: '<p>这次旅行让我收获颇丰，见识了不同的风土人情...</p>',
    status: 'published',
    createdAt: '2024-01-10',
    updatedAt: '2024-01-10'
  }
];

// API路由

// 获取所有文章
app.get('/api/articles', (req, res) => {
  const { status, category } = req.query;
  let filteredArticles = articles;
  
  if (status) {
    filteredArticles = filteredArticles.filter(article => article.status === status);
  }
  
  if (category) {
    filteredArticles = filteredArticles.filter(article => article.category === category);
  }
  
  res.json({
    success: true,
    data: filteredArticles,
    total: filteredArticles.length
  });
});

// 获取单个文章
app.get('/api/articles/:id', (req, res) => {
  const article = articles.find(a => a.id === parseInt(req.params.id));
  if (!article) {
    return res.status(404).json({
      success: false,
      message: '文章不存在'
    });
  }
  
  res.json({
    success: true,
    data: article
  });
});

// 创建新文章
app.post('/api/articles', (req, res) => {
  const { title, category, theme, keywords, content, status = 'draft' } = req.body;
  
  if (!title || !content) {
    return res.status(400).json({
      success: false,
      message: '标题和内容不能为空'
    });
  }
  
  const newArticle = {
    id: articles.length > 0 ? Math.max(...articles.map(a => a.id)) + 1 : 1,
    title,
    category: category || 'technology',
    theme: theme || '',
    keywords: keywords || '',
    content,
    status,
    createdAt: new Date().toISOString().split('T')[0],
    updatedAt: new Date().toISOString().split('T')[0]
  };
  
  articles.push(newArticle);
  
  res.status(201).json({
    success: true,
    message: status === 'published' ? '文章发布成功' : '草稿保存成功',
    data: newArticle
  });
});

// 更新文章
app.put('/api/articles/:id', (req, res) => {
  const articleIndex = articles.findIndex(a => a.id === parseInt(req.params.id));
  if (articleIndex === -1) {
    return res.status(404).json({
      success: false,
      message: '文章不存在'
    });
  }
  
  const { title, category, theme, keywords, content, status } = req.body;
  
  articles[articleIndex] = {
    ...articles[articleIndex],
    ...(title && { title }),
    ...(category && { category }),
    ...(theme && { theme }),
    ...(keywords && { keywords }),
    ...(content && { content }),
    ...(status && { status }),
    updatedAt: new Date().toISOString().split('T')[0]
  };
  
  res.json({
    success: true,
    message: '文章更新成功',
    data: articles[articleIndex]
  });
});

// 删除文章（移至回收站）
app.delete('/api/articles/:id', (req, res) => {
  const articleIndex = articles.findIndex(a => a.id === parseInt(req.params.id));
  if (articleIndex === -1) {
    return res.status(404).json({
      success: false,
      message: '文章不存在'
    });
  }
  
  articles[articleIndex].status = 'deleted';
  
  res.json({
    success: true,
    message: '文章已移至回收站'
  });
});

// 恢复文章
app.patch('/api/articles/:id/restore', (req, res) => {
  const articleIndex = articles.findIndex(a => a.id === parseInt(req.params.id));
  if (articleIndex === -1) {
    return res.status(404).json({
      success: false,
      message: '文章不存在'
    });
  }
  
  articles[articleIndex].status = 'draft';
  
  res.json({
    success: true,
    message: '文章已恢复'
  });
});

// 永久删除文章
app.delete('/api/articles/:id/permanent', (req, res) => {
  const articleIndex = articles.findIndex(a => a.id === parseInt(req.params.id));
  if (articleIndex === -1) {
    return res.status(404).json({
      success: false,
      message: '文章不存在'
    });
  }
  
  articles.splice(articleIndex, 1);
  
  res.json({
    success: true,
    message: '文章已永久删除'
  });
});

// 文件上传接口（用于富文本编辑器）
app.post('/api/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({
      success: false,
      message: '没有上传文件'
    });
  }
  
  res.json({
    success: true,
    data: {
      url: `/uploads/${req.file.filename}`,
      name: req.file.originalname,
      size: req.file.size
    }
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        success: false,
        message: '文件大小超过限制'
      });
    }
  }
  
  res.status(500).json({
    success: false,
    message: error.message || '服务器内部错误'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log('API文档: http://localhost:3000/api/articles');
});